package org.thirdeye.reader.helper;

import java.util.ArrayList;

import org.thirdeye.reader.ThirdEye_TextReaderDTO;
import org.thirdeye.reader.constants.ApplicationConstants;

import android.speech.tts.TextToSpeech;
import android.util.Log;


public class Reader {
	private ThirdEye_TextReaderDTO data;
	private TextToSpeech tts;

	public Reader(ThirdEye_TextReaderDTO data, TextToSpeech tts) {
		this.data = data;
		this.tts = tts;
	}

	public String readCurrentPage() {
		data.setCurSentence(0);
		PageReader fromPageObj = new PageReader(data,tts);
		data.setAction(ApplicationConstants.START);
		fromPageObj.read(data.getCurPage(), data.getCurPage());
		return loadSentences();
	}

	public String readFromPage(int pageNo) {
		data.setCurSentence(0);
		PageReader fromPageObj = new PageReader(data, tts);
		data.setAction(ApplicationConstants.START);
		fromPageObj.read(pageNo, data.getPageCnt());
		return loadSentences();
	}

	public String readAllPages() {
		data.setCurSentence(0);
		data.setCurPage(0);
		PageReader fromPageObj = new PageReader(data, tts);
		data.setAction(ApplicationConstants.START);
		fromPageObj.read(data.getCurPage(), data.getPageCnt());
		return loadSentences();
	}
	
	public String loadSentences() {
		Log.d("Entering:", "loadSentences()");
		if (data.getSentences() != null) {
			int i = 0;
			StringBuffer buf = new StringBuffer();
			int sentenceLength = data.getSentences().length;
			int curPage = data.getCurPage();
			while (i < data.getSentenceCnt()
					&& ((i + (curPage * ApplicationConstants.MAX_SENTENCES)) < sentenceLength)) {
				buf.append(data.getSentences()[i
						+ (curPage * ApplicationConstants.MAX_SENTENCES)]
						+ "\n");
				i++;
			}
			String[] pageSentencesArray = buf.toString().split("\n");
			ArrayList<String> pageSentences = new ArrayList<String>();
			for (String pageSentence : pageSentencesArray) {
				pageSentences.add(pageSentence);
			}
			data.setPageSentences(pageSentences);
			return buf.toString();
		}
		return null;

	}
}
